package edu.nf.ch01.common;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import java.io.InputStream;

/**
 * @ClassName MinioUtils
 * @Description Minio 工具类
 * @Author Kx
 * @Date 2025/9/4 19:02
 * @Version 1.0
 */
public class MinioUtils {
    // 连接属性
    private static final String HOST = "http://127.0.0.1:9000"; // 客户端访问地址
    private static final String ACCOUNT = "minioadmin"; // 账号
    private static final String PASSWORD = "minioadmin"; // 密码
    // Minio客户端
    private static MinioClient client;

    /** 
     * @author: kx
     * @date: 2025/9/4 19:06
     * @param null 
     * @return
     * @description: 初始化客户端
    */
    static {
        client = MinioClient.builder().endpoint(HOST).credentials(ACCOUNT,PASSWORD).build();
    }

    /**
     * @author: kx
     * @date: 2025/9/4 19:07
     * @param bucketName : 存储桶名称
     * @return boolean
     * @description: 判断桶是否存在
    */
    public static boolean hasBucket(String bucketName) {
        try {
            return client.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * @author: kx
     * @date: 2025/9/4 19:11
     * @param bucketName : 存储桶名称
     * @description: 创建桶
    */
    public static void createBucket(String bucketName) {
        try {
            client.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @author: kx
     * @date: 2025/9/4 19:13
     * @param bucketName : 存储桶名称
     * @param objectPath : 对象路径
     * @param contentType : 文件类型
     * @param size : 文件大小
     * @param input : 文件输入流
     * @description: 文件上传
    */
    public static void upload(String bucketName, String objectPath, String contentType, Long size, InputStream input) {
        try {
            client.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectPath).contentType(contentType).stream(input, size, -1).build());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
